package com.ruoyi.quartz.task;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.plan.domain.PlanSubject;
import com.ruoyi.plan.domain.ReviewPlan;
import com.ruoyi.plan.domain.StudyContent;
import com.ruoyi.plan.mapper.ReviewPlanMapper;
import com.ruoyi.plan.service.IPlanSubjectService;
import com.ruoyi.plan.service.IReviewPlanService;
import com.ruoyi.plan.service.IStudyContentService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author MLYNDHG
 * @version 1.0
 * @description 学习定时任务调度
 * @date 2023/12/8 14:30
 */
@Component("LuxifelTask")
public class LuxifelTask {
    @Autowired
    private IPlanSubjectService planSubjectService;

    @Autowired
    private IReviewPlanService reviewPlanService;

    @Autowired
    private ReviewPlanMapper reviewPlanMapper;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private IStudyContentService studyContentService;

    public void ryTest()
    {
        System.out.println("执行ryTestryTestryTestryTestryTestryTestryTestryTestryTest方法");
    }

    /**
     * 凌晨定时任务2  将学习内容加入复习计划中  每日  23：55
     * 1.studyStatus字段为已经学习 的加入 复习计划中
     * 2.将markStatus的值同步为studyStatus
     * @return 复习计划
     * @param  errorTodayDate 服务器太小导致数据库崩溃时，任务未执行，手动填入参数，手动执行一次，不填则正常执行  'yyyy-MM-dd'
     */
    public void schduleTodyReview(String errorTodayDate)  {
        Date date = new Date();
        Date today = new Date(date.getTime());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formaTodayDate = dateFormat.format(today);
        //明日日期
        Calendar calendar = Calendar.getInstance(); // 获取一个Calendar对象
        calendar.add(Calendar.DATE, 1); // 给当前日期加上一天
        Date tomorrow = calendar.getTime();
        String formaTomorrowDate = dateFormat.format(tomorrow);

        //手动执行 则日期使用参数
        if(!errorTodayDate.equals("")){
            formaTodayDate = errorTodayDate;

            try {
                // 创建一个日期格式化对象
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                // 将日期字符串解析为日期对象
                Date date2 = format.parse(errorTodayDate);
                // 创建一个日历对象
                Calendar calendar2 = Calendar.getInstance();
                // 设置日历对象的时间为日期对象
                calendar.setTime(date2);
                // 将日历对象的天数加一
                calendar.add(Calendar.DAY_OF_YEAR, 1);
                // 将日历对象的时间格式化为日期字符串
                formaTomorrowDate = format.format(calendar.getTime());
            }catch (Exception e) {
                // 如果发生异常，打印异常信息，并返回空字符串
                e.printStackTrace();
            }
        }


        StudyContent studyContent = new StudyContent();
        studyContent.setStudyStatus("1");

        List<StudyContent> studyContentList = studyContentService.selectStudyContentList(studyContent);

        for (int i = 0; i < studyContentList.size(); i++) {
            PlanSubject planSubject = planSubjectService.selectPlanSubjectById(studyContentList.get(i).getSubjectId());

            ReviewPlan reviewPlan = new ReviewPlan();
            reviewPlan.setUid(planSubject.getUid());
            reviewPlan.setStudyContentId(studyContentList.get(i).getId());
            reviewPlan.setStudyContentTitle(studyContentList.get(i).getTitle());
            reviewPlan.setCreateDate(formaTodayDate);
            reviewPlan.setReviewDate(formaTomorrowDate);//初次加入复习都定为第二天复习
            reviewPlan.setReviewStatus("0");
            reviewPlan.setReviewCycle(1L);
            reviewPlan.setReviewNote("");
            reviewPlan.setDescribes("");
            reviewPlanService.insertReviewPlan(reviewPlan);

            //更改今日显示状态
            StudyContent studyContent1 = studyContentList.get(i);
            studyContent1.setMarkStatus(studyContent1.getStudyStatus());
            studyContentService.updateStudyContent(studyContent1);
        }
//        将学习状态重新设置
        StudyContent studyContent2 = new StudyContent();
        studyContent2.setStudyStatus("1");
        List<StudyContent> studyContentList2 = studyContentService.selectStudyContentList(studyContent2);
        for (int i = 0; i < studyContentList2.size(); i++) {
            StudyContent studyContent3 = studyContentList2.get(i);
            studyContent3.setStudyStatus("0");
            studyContentService.updateStudyContent(studyContent3);
        }
    };

    /**
     * 凌晨定时任务1  将复习计划按照今日完成情况重新计算    每日  23：40
     *  1.今日复习任务还有未完成的项时  将所有未完成的项的计划复习日期向后延一天
     *  2.今日复习任务全部完成的话，将今日的任务按照复习轮次再次计划复习日期
     *  3.将状态全部变为未学习
     *  @return 复习计划
     *  @param  errorTodayDate 服务器太小导致数据库崩溃时，任务未执行，手动填入参数，手动执行一次，不填则正常执行  'yyyy-MM-dd'
     */
    public void schduleTodyReviewPlan(String errorTodayDate){
        List<Long> list2 = new ArrayList<>(Arrays.asList(1L, 3L, 5L, 8L, 15L, 30L, 60L));
        Date date = new Date();
        Date today = new Date(date.getTime());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formaTodayDate = dateFormat.format(today);
        //手动执行 则日期使用参数
        if(!errorTodayDate.equals("")){
            formaTodayDate = errorTodayDate;
        }

        //定时任务无法获取用户  所以要将所有用户进行遍历
        SysUser user = new SysUser();
        List<SysUser> userList = userMapper.selectUserList(user);
        for (int i = 0; i < userList.size(); i++) {
            Long userId = userList.get(i).getUserId();
            //
            ReviewPlan reviewPlanBool = new ReviewPlan();
            reviewPlanBool.setReviewDate(formaTodayDate);
            reviewPlanBool.setReviewStatus("0");
            reviewPlanBool.setUid(userId);
            List<ReviewPlan> reviewPlanListBool = reviewPlanMapper.selectReviewPlanList(reviewPlanBool);
            //查询今日是否有未完成复习的事件  将未复习完将日期后延  完成复习的重新计算下次复习日期
            if(reviewPlanListBool.size()>0)
            {
                //1.今日未完成的
                ReviewPlan reviewPlan = new ReviewPlan();
                reviewPlan.setReviewStatus("0");//将所有状态为未完成的事件向后挪一天
                reviewPlan.setUid(userId);
                List<ReviewPlan> reviewPlanList = reviewPlanMapper.selectReviewPlanList(reviewPlan);
                for (int j = 0; j < reviewPlanList.size(); j++) {
                    ReviewPlan plan = reviewPlanList.get(j);
                    Date reviewDate = null;
                    try {
                        reviewDate = dateFormat.parse(plan.getReviewDate());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long time = reviewDate.getTime(); // 获取当前日期的毫秒值
                    time = time + 24 * 60 * 60 * 1000; // 加上一天的毫秒数
                    reviewDate.setTime(time); // 设置后一天的毫秒值
                    String formatReviewDateDate = dateFormat.format(reviewDate);
                    plan.setReviewDate(formatReviewDateDate);
                    reviewPlanService.updateReviewPlan(plan);
                }
                //2.今日已完成的
                ReviewPlan reviewPlanFinish = new ReviewPlan();
                reviewPlanFinish.setReviewDate(formaTodayDate);
                reviewPlanFinish.setReviewStatus("1");
                reviewPlanFinish.setUid(userId);
                List<ReviewPlan> reviewPlanListFinish = reviewPlanMapper.selectReviewPlanList(reviewPlanFinish);
                for (int j = 0; j < reviewPlanListFinish.size(); j++) {
                    ReviewPlan planTodayFinish = reviewPlanListFinish.get(j);
                    Long aLong = list2.get(Math.toIntExact(planTodayFinish.getReviewCycle()));
                    if(planTodayFinish.getReviewCycle() > 6){
                        //如果这个事件已经复习轮次大于六次了  就不再参加计划了
                        continue;
                    }
                    Date reviewDate = null;
                    try {
                        reviewDate = dateFormat.parse(planTodayFinish.getReviewDate());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long time = reviewDate.getTime(); // 获取当前日期的毫秒值
                    time = time + aLong * 24 * 60 * 60 * 1000; // 加上一天的毫秒数
                    reviewDate.setTime(time);
                    String formatReviewDateDate = dateFormat.format(reviewDate);
                    planTodayFinish.setReviewDate(formatReviewDateDate);

                    planTodayFinish.setReviewCycle(planTodayFinish.getReviewCycle()+1);

                    reviewPlanService.updateReviewPlan(planTodayFinish);
                }
            }
            else
            {
                ReviewPlan reviewPlanToday = new ReviewPlan();
                reviewPlanToday.setReviewDate(formaTodayDate);
                reviewPlanToday.setUid(userId);
                List<ReviewPlan> reviewPlanListToday = reviewPlanMapper.selectReviewPlanList(reviewPlanToday);
                for (int j = 0; j < reviewPlanListToday.size(); j++) {
                    ReviewPlan planToday = reviewPlanListToday.get(j);
                    Long aLong = list2.get(Math.toIntExact(planToday.getReviewCycle()));
                    if(planToday.getReviewCycle() > 6){
                        //如果这个事件已经复习轮次大于六次了  就不再参加计划了
                        continue;
                    }
                    Date reviewDate = null;
                    try {
                        reviewDate = dateFormat.parse(planToday.getReviewDate());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long time = reviewDate.getTime(); // 获取当前日期的毫秒值
                    time = time + aLong * 24 * 60 * 60 * 1000; // 加上一天的毫秒数
                    reviewDate.setTime(time);
                    String formatReviewDateDate = dateFormat.format(reviewDate);
                    planToday.setReviewDate(formatReviewDateDate);

                    planToday.setReviewCycle(planToday.getReviewCycle()+1);

                    reviewPlanService.updateReviewPlan(planToday);
                }
            }

            //将状态全部修改为  1
            ReviewPlan reviewPlanInitialStatus = new ReviewPlan();
            reviewPlanInitialStatus.setReviewStatus("1");
            reviewPlanInitialStatus.setUid(userId);
            List<ReviewPlan> reviewPlanListInitialStatus = reviewPlanMapper.selectReviewPlanList(reviewPlanInitialStatus);

            for (int j = 0; j < reviewPlanListInitialStatus.size(); j++)
            {
                ReviewPlan planInitialStatus = reviewPlanListInitialStatus.get(j);
                planInitialStatus.setReviewStatus("0");
                reviewPlanService.updateReviewPlan(planInitialStatus);
            }
        }
    };
}
